from util.Route import *
from service import SignService,UserManageService
@route("/test")
def test():
    print(getUserRemoteAddr())
    return 'test'
@route("/captcha")
def captcha():
    r = SignService.getCaptcha()
    return R.success(data=r)

@route("/sign/in", methods = ['POST'])
def login():
    req = request.json
    try:
        # 人机验证
        r = SignService.authCaptcha(req.get('token'),req.get('code'),1,True)
        if(r==None):
            return R.bad_request("验证码已过期")
        elif r==False:
            return R.bad_request("验证码错误")
        # 登陆
        r = SignService.signIn(req['username'],req['password'])
        if(r == 0):
            return R.unauthorized("账号或密码错误")
        elif(r == 1):
            return R.unauthorized("账号已被锁定")
        return R.success(r,"成功")
    except Exception as e:
        raise e
    
@route("/sign/up",methods = ["POST"])
def sginUp():
    req:dict = request.json
    r = SignService.authCaptcha(req['token'],req['code'])
    if(r==None):
        return R.bad_request("验证码已过期")
    elif r==False:
        return R.bad_request("验证码错误")
    req.pop('code')
    req.pop('token')
    r = SignService.signUp(req)
    if(r==0):
        return R.create(400,msg="用户已存在请重新输入用户名")
    return R.success(msg='注册成功')
    
    
@route("/sign/has/user",methods = ["POST"])
def hasUser():
    user = request.args.get("username")
    hs = SignService.hasUser(user)
    return R.create(200,hs)

# 用户选择角色登陆登陆
@route("/sign/role")
def roleLogin():
    uid = request.environ.get("UID")
    rid = request.args.get("rid")
    r = SignService.roleSignIn(uid,rid)
    if r:
        return R.success(r)
    return R.bad_request('登陆失败')
